'use client'

import { useState, useEffect } from 'react'
import { VmsCopy, VmsTopic } from '@/types/Model'
import { Button } from '@/components/ui/button'
import { toast } from '@/hooks/use-toast'
import { Input } from '@/components/ui/input'
import { Search, ChevronDown, Check } from 'lucide-react'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'

interface CopySelectorProps {
  copies: VmsCopy[]
  onCancel: () => void
  onSubmit: (copyIds: string[]) => void
}

export default function CopySelector({ copies, onCancel, onSubmit }: CopySelectorProps) {
  const [selectedCopies, setSelectedCopies] = useState<string[]>([])
  const [topics, setTopics] = useState<VmsTopic[]>([])
  const [selectedTopicId, setSelectedTopicId] = useState<string>('all')
  const [searchTerm, setSearchTerm] = useState('')
  const [filteredCopies, setFilteredCopies] = useState<VmsCopy[]>(copies)
  const [loading, setLoading] = useState(false)
  
  // 新增：项目搜索相关状态
  const [topicSearchTerm, setTopicSearchTerm] = useState('')
  const [isTopicDropdownOpen, setIsTopicDropdownOpen] = useState(false)
  const [filteredTopics, setFilteredTopics] = useState<VmsTopic[]>([])

  // 获取用户的所有项目
  useEffect(() => {
    const fetchTopics = async () => {
      try {
        setLoading(true)
        const token = localStorage.getItem('token')
        const response = await fetch('/api/topic', {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (response.ok) {
          const topicsData = await response.json()
          setTopics(topicsData)
          setFilteredTopics(topicsData)
        }
      } catch (error) {
        console.error('获取项目失败:', error)
      } finally {
        setLoading(false)
      }
    }

    fetchTopics()
  }, [])

  // 筛选项目列表
  useEffect(() => {
    if (topicSearchTerm.trim()) {
      const term = topicSearchTerm.toLowerCase()
      const filtered = topics.filter(topic => 
        (topic.name || topic.title || '未命名项目').toLowerCase().includes(term)
      )
      setFilteredTopics(filtered)
    } else {
      setFilteredTopics(topics)
    }
  }, [topics, topicSearchTerm])

  // 筛选文案
  useEffect(() => {
    let filtered = copies

    // 按项目筛选
    if (selectedTopicId !== 'all') {
      filtered = filtered.filter(copy => copy.topic_id === selectedTopicId)
    }

    // 按搜索词筛选
    if (searchTerm.trim()) {
      const term = searchTerm.toLowerCase()
      filtered = filtered.filter(copy => 
        copy.title?.toLowerCase().includes(term) 
      )
    }

    setFilteredCopies(filtered)
  }, [copies, selectedTopicId, searchTerm])

  const handleSubmit = () => {
    if (selectedCopies.length === 0) {
      toast({
        title: '请选择文案',
        description: '至少选择一个文案来创建小节',
        variant: 'destructive'
      })
      return
    }
    onSubmit(selectedCopies)
  }

  const handleSelectAll = () => {
    if (selectedCopies.length === filteredCopies.length) {
      setSelectedCopies([])
    } else {
      setSelectedCopies(filteredCopies.map(copy => copy.id))
    }
  }

  // 获取选中项目的显示名称
  const getSelectedTopicName = () => {
    if (selectedTopicId === 'all') return '所有项目'
    const topic = topics.find(t => t.id === selectedTopicId)
    return topic?.name || topic?.title || '未命名项目'
  }

  // 处理项目选择
  const handleTopicSelect = (topicId: string) => {
    setSelectedTopicId(topicId)
    setIsTopicDropdownOpen(false)
    setTopicSearchTerm('')
  }

  return (
    <div className="space-y-4">
      {/* 筛选器区域 - 左右布局 */}
      <div className="p-4 bg-slate-50 rounded-lg">
        <h3 className="font-medium text-slate-900 mb-3">筛选条件</h3>
        
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* 左侧：项目筛选 - 自定义搜索下拉 */}
          <div className="space-y-2">
            <label className="text-sm font-medium text-slate-700">选择项目</label>
            <Popover open={isTopicDropdownOpen} onOpenChange={setIsTopicDropdownOpen}>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  role="combobox"
                  aria-expanded={isTopicDropdownOpen}
                  className="w-full justify-between"
                >
                  {getSelectedTopicName()}
                  <ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-full p-0" align="start">
                <div className="p-2">
                  <div className="relative">
                    <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 text-slate-400 h-4 w-4" />
                    <Input
                      placeholder="搜索项目..."
                      value={topicSearchTerm}
                      onChange={(e) => setTopicSearchTerm(e.target.value)}
                      className="pl-8"
                    />
                  </div>
                </div>
                <div className="max-h-60 overflow-y-auto">
                  <div
                    className={`flex items-center px-3 py-2 cursor-pointer hover:bg-slate-100 ${
                      selectedTopicId === 'all' ? 'bg-slate-100' : ''
                    }`}
                    onClick={() => handleTopicSelect('all')}
                  >
                    <Check
                      className={`mr-2 h-4 w-4 ${
                        selectedTopicId === 'all' ? 'opacity-100' : 'opacity-0'
                      }`}
                    />
                    所有项目
                  </div>
                  {filteredTopics.map((topic) => {
                    const topicName = topic.name || topic.title || '未命名项目'
                    return (
                      <div
                        key={topic.id}
                        className={`flex items-center px-3 py-2 cursor-pointer hover:bg-slate-100 ${
                          selectedTopicId === topic.id ? 'bg-slate-100' : ''
                        }`}
                        onClick={() => handleTopicSelect(topic.id)}
                      >
                        <Check
                          className={`mr-2 h-4 w-4 ${
                            selectedTopicId === topic.id ? 'opacity-100' : 'opacity-0'
                          }`}
                        />
                        {topicName}
                      </div>
                    )
                  })}
                  {filteredTopics.length === 0 && topicSearchTerm && (
                    <div className="px-3 py-2 text-sm text-slate-500">
                      没有找到匹配的项目
                    </div>
                  )}
                </div>
              </PopoverContent>
            </Popover>
          </div>

          {/* 右侧：文案搜索 */}
          <div className="space-y-2">
            <label className="text-sm font-medium text-slate-700">搜索文案</label>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 h-4 w-4" />
              <Input
                placeholder="搜索文案标题或内容..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
        </div>
      </div>

      {/* 文案列表 */}
      <div className="space-y-2">
        <div className="flex justify-between items-center">
          <span className="text-sm text-slate-600">
            找到 {filteredCopies.length} 个文案
          </span>
          {filteredCopies.length > 0 && (
            <Button
              variant="outline"
              size="sm"
              onClick={handleSelectAll}
            >
              {selectedCopies.length === filteredCopies.length ? '取消全选' : '全选'}
            </Button>
          )}
        </div>

        <div className="max-h-96 overflow-y-auto space-y-2">
          {loading ? (
            <div className="text-center py-8 text-slate-500">
              加载中...
            </div>
          ) : filteredCopies.length === 0 ? (
            <div className="text-center py-8 text-slate-500">
              {searchTerm || selectedTopicId !== 'all' ? '没有找到匹配的文案' : '暂无文案'}
            </div>
          ) : (
            filteredCopies.map((copy) => {
              const topicName = topics.find(t => t.id === copy.topic_id)?.name || 
                              topics.find(t => t.id === copy.topic_id)?.title || 
                              copy.topic_name || '未知项目'
              
              return (
                <div key={copy.id} className="flex items-center space-x-3 p-3 border rounded-lg hover:bg-slate-50">
                  <input
                    type="checkbox"
                    checked={selectedCopies.includes(copy.id)}
                    onChange={(e) => {
                      if (e.target.checked) {
                        setSelectedCopies(prev => [...prev, copy.id])
                      } else {
                        setSelectedCopies(prev => prev.filter(id => id !== copy.id))
                      }
                    }}
                    className="rounded border-slate-300 text-rose-600 focus:ring-rose-500"
                  />
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-1">
                      <h4 className="font-medium text-slate-900">{copy.title}</h4>
                      <span className="text-xs px-2 py-1 bg-blue-100 text-blue-700 rounded">
                        {topicName}
                      </span>
                    </div>
                    {copy.rich_content && (
                      <p className="text-sm text-slate-600 line-clamp-2">
                        {copy.rich_content.length > 100 ? 
                          `${copy.rich_content.substring(0, 100)}...` : 
                          copy.rich_content}
                      </p>
                    )}
                    {copy.intro && (
                      <p className="text-xs text-slate-500 mt-1">
                        {copy.intro}
                      </p>
                    )}
                  </div>
                </div>
              )
            })
          )}
        </div>
      </div>
      
      <div className="flex justify-between items-center pt-4 border-t">
        <span className="text-sm text-slate-600">
          已选择 {selectedCopies.length} 个文案
        </span>
        <div className="flex gap-2">
          <Button variant="outline" onClick={onCancel}>
            取消
          </Button>
          <Button 
            onClick={handleSubmit}
            disabled={selectedCopies.length === 0}
            className="bg-gradient-to-r from-rose-600 to-rose-700 hover:from-rose-700 hover:to-rose-800 text-white"
          >
            创建小节
          </Button>
        </div>
      </div>
    </div>
  )
}